<template>
  <div>
    <ListTab v-if="!showMobilePage" show-header />
    <div :class="{'mobile-table mobile-min-height':showMobilePage}" class="legal-process-container">
      <div v-if="!showMobilePage" class="legal-top">
        <el-button style="margin-right: 10px;" size="small" type="primary" @click="createProcess">新建表单流程</el-button>
        <MoreOpeator
          ref="btnGroupRef"
          :label="'更多操作'"
          :list="[
            { label: '分组管理', handelClick: groupOperateShow },
            { label: '批量设置人员', handelClick: batchAdd }
          ]"
        />
      </div>
      <div v-loading="listLoading" class="legal-table">
        <el-table
          v-if="list.length > 0"
          ref="legalTableRef"
          :data="list"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          :height="setTableHeight"
          :row-style="{ height: '46px' }"
          default-expand-all
          row-key="id"
          class="fb-table"
          element-loading-text="加载中..."
          empty-text="暂无数据"
          header-cell-class-name="order-data-header-cell"
          fit
          @row-click="getOpenDetail">
          <el-table-column width="240px" align="left" label="流程名称" prop="name">
            <template slot-scope="scope">
              <div class="flex">
                <div v-if="scope.row.icon" :style="{ background: scope.row.iconColor || defaultColor }" class="module-icon">
                  <img :src="getIcon(scope.row.icon)">
                </div>
                <ToolTip :content=" scope.row.name" class=""/>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="表单类型" min-width="160px">
            <template slot-scope="scope">
              <div v-if="!isShow(scope.row.id)" class="flex">
                <div>{{ scope.row.isCustom ? '自定义表单流程' : '固定表单流程' }}</div>
                <img :src="scope.row.isCustom ? custom : form" style="margin: -1px 0 0 3px;width: 14px;" alt="process" >
              </div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="管理员" min-width="120">
            <template slot-scope="scope">
              <div v-if="!isShow(scope.row.id)" class="flex-center">
                <div v-if="scope.row.adminList && scope.row.adminList.length && scope.row.adminList.length !== 1" class="pointer-class" @click="showUserInfoDialog(0, scope.row.adminList)">{{ scope.row.adminList.length }}</div>
                <div v-if="scope.row.adminList && scope.row.adminList.length && scope.row.adminList.length === 1" class="pointer-class">
                  <CheckUserInfo :label="scope.row.administrator" :user-id="scope.row.administratorId">
                    <span class="mr5 pointer-class">{{ scope.row.administrator || '--' }}</span>
                  </CheckUserInfo>
                  <el-tooltip placement="top">
                    <div slot="content">管理员可配置表单权限给其他人员，<br>转交后你将没有权限编辑该表单</div>
                    <img v-if="scope.row.isCustom && scope.row.administratorId === id" :src="transform" class="img-icon" style="position: relative;top: 2px;" @click="transferAdministrator(scope.row)">
                  </el-tooltip>
                </div>
                <div v-else-if="!scope.row.adminList || !scope.row.adminList.length">
                  <CheckUserInfo :label="scope.row.administrator" :user-id="scope.row.administratorId">
                    <span class="mr5 pointer-class">{{ scope.row.administrator || '--' }}</span>
                  </CheckUserInfo>
                  <el-tooltip placement="top">
                    <div slot="content">管理员可配置表单权限给其他人员，<br>转交后你将没有权限编辑该表单</div>
                    <img v-if="scope.row.isCustom && scope.row.administratorId === id" :src="transform" class="img-icon" @click="transferAdministrator(scope.row)">
                  </el-tooltip>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="可见人员" min-width="120">
            <template slot-scope="scope">
              <div v-if="!isShow(scope.row.id)">
                <div v-if="scope.row.isAllVisible">全员可见</div>
                <div v-else-if="scope.row.visibleStaffNum && scope.row.visibleStaffNum !== 1" class="pointer-class" @click="showUserInfoDialog(1, scope.row.visibleStaffList)">{{ scope.row.visibleStaffNum === 1 ? scope.row.visibleStaffList[0].value : scope.row.visibleStaffNum }}</div>
                <CheckUserInfo v-else-if="scope.row.singleVisibleName" :label="scope.row.singleVisibleName" :user-id="scope.row.singleVisibleId">
                  <span class="mr5 pointer-class">{{ scope.row.singleVisibleName }}</span>
                </CheckUserInfo>
                <div v-else>--</div>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="left" label="激活时间" min-width="180">
            <template slot-scope="scope">
              <span v-if="isShow(scope.row.id)" />
              <span v-else>{{ scope.row.activationTime | format('YYYY/MM/DD HH:mm:ss') }}</span>
            </template>
          </el-table-column>
          <el-table-column :min-width="operateWidth" align="left" label="操作" fixed="right">
            <template slot-scope="scope">
              <div v-if="isShow(scope.row.id)" />
              <template v-else>
                <div v-if="!showMobilePage" class="flex-center">
                  <el-button
                    :disabled="!canDesignForm(scope.row)"
                    type="text"
                    @click="toEdit(scope.row)">
                    <span :style="{ color: canDesignForm(scope.row) ? '#406EFF' : '#ccc' }" style="font-size:14px;">编辑</span>
                  </el-button>
                  <template v-if="scope.row.isCustom">
                    <div class="border-left" />
                    <el-button
                      :disabled="!canDesignForm(scope.row)"
                      type="text"
                      @click="handleProcessDel(scope.row)">
                      <span :style="{ color: canDesignForm(scope.row) ? 'red' : '#ccc' }" style="font-size:14px;">删除</span>
                    </el-button>
                  </template>
                </div>
                <tableOperateBtn v-else>
                  <el-dropdown-item :disabled="!canDesignForm(scope.row)" style="width:90px;text-align: center" @click.native="toEdit(scope.row)">
                    <div style="font-size: 14px">编辑</div>
                  </el-dropdown-item>
                  <el-dropdown-item :disabled="!canDesignForm(scope.row)" style="width:90px;text-align: center" @click.native="handleProcessDel(scope.row)">
                    <div style="font-size: 14px">删除</div>
                  </el-dropdown-item>
                </tableOperateBtn>
              </template>
            </template>
          </el-table-column>
        </el-table>
        <empty-placeholder v-else-if="!isInit" style="margin-bottom: 24px" />
      </div>
      <fixed-pagination v-if="showMobilePage">
        <MoreOpeator
          ref="btnGroupRef"
          :label="'更多操作'"
          :list="[
            { label: '分组管理', handelClick: groupOperateShow },
            { label: '批量设置人员', handelClick: batchAdd }
          ]"
          style="flex: 1"
        />
        <CreateBtn
          mobile-table
          style="flex: 1"
          text="新建表单流程"
          @click.native="createProcess"/>
      </fixed-pagination>
    </div>
    <batchAddDialog ref="batchAdd" :process-list="processList" />
    <GroupListDialog
      ref="groupListRef"
      v-model="list"
      :list-loading="listLoading"
      @resetList="getData"
      @handleGroupDel="handleGroupDel"
      @editDialogShow="editDialogShow"/>
    <GroupEditDialog
      ref="groupEditRef"
      @groupAdd="handleGroupAdd"
      @groupEdit="handleGroupEdit"
      @closeCallback="groupOperateShow"/>
    <DiversAuditorDialog
      ref="auditorDialog"
      @userSelect="sumbmitDeliverTo" />
    <UserInfoDialog
      ref="userInfoDialogRef"
      :show-mobile-page="showMobilePage"
      :title="userDialogTitle"
      :list="userList"
      @closeDialog="closeUserInfoDialog"
    />
  </div>
</template>

<script>
// 组件
import DiversAuditorDialog from '@/components/Common/auditProcess/module/diversAuditorDialog';
import MoreOpeator from '@/components/Common/baseComponent/moreOpeator';
import EmptyPlaceholder from '@/components/EmptyPlaceholder';
import ListTab from '@/components/ListTab';
import CreateBtn from '@/components/Common/baseComponent/createBtn';
import batchAddDialog from './components/batchAdd';
import GroupListDialog from './components/groupListDialog';
import GroupEditDialog from './components/groupEditDialog';
import UserInfoDialog from '@/components/Common/UserInfoDialog';
// tool
import ElMessage, { showModal } from '@/utils/message';
import {
  getProcessManagement,
  addProcessManagement,
  editProcessManagement,
  deleteProcessGroup,
  deleteProcess,
  transferAdministrator,
  getVisibleStaffList
} from '@/api/legal';
import iconConfig from '@/mixins/iconConfig';
import mobileTable from '@/mixins/mobileTable';
import { format } from '@/filters/date';
import setting from '@/assets/setting.png';
import transform from '@/assets/process/transform.png';
import form from '@/assets/process/form.png';
import custom from '@/assets/process/custom.png';
import { hasRouteAuth } from '@/utils/permission';
import { mapState } from 'vuex';

export default {
  components: {
    MoreOpeator,
    EmptyPlaceholder,
    ListTab,
    CreateBtn,
    batchAddDialog,
    GroupListDialog,
    GroupEditDialog,
    DiversAuditorDialog,
    UserInfoDialog
  },
  filters: { format },
  mixins: [iconConfig, mobileTable],
  data() {
    return {
      setting,
      transform,
      form,
      custom,
      list: [],
      userList: [],
      listLoading: false,
      isInit: true,
      processList: [],
      firstLevelIds: [],
      transferParam: {},
      userDialogTitle: ''
    };
  },
  computed: {
    ...mapState({
      'id': state => state.user.id,
      'showMobilePage': state => state.app.showMobilePage
    }),
    setTableHeight() {
      return `calc(100vh - ${this.showMobilePage ? 112 : 160}px)`;
    }
  },
  beforeRouteEnter(to, from, next) {
    to.meta.isChange = from.name === 'ContractProcessEditCustom';
    next();
  },
  created() {
    this.getData();
  },
  methods: {
    getData() {
      this.listLoading = true;
      getProcessManagement().then(res => {
        this.listLoading = false;
        this.isInit = false;
        if (res.code === 200) {
          this.list = res.data || [];
          this.$store.commit('SET_GROUP_LIST', res.data);
          this.setProcessList();
          this.setFirstLevelIds();
        } else {
          ElMessage.error(res.message);
        }
      }).catch(_ => {
        this.listLoading = false;
      });
    },
    // 获取所有的子流程
    setProcessList() {
      this.processList = [];
      this.list.forEach(item => {
        if (Array.isArray(item.children) && item.children.length) {
          this.processList = this.processList.concat(item.children || []);
        }
      });
      this.processList.unshift({ id: -1, name: '全部' });
    },
    // 获取所有的分类id
    setFirstLevelIds() {
      this.firstLevelIds = this.list.map(item => item.id);
    },
    closeUserInfoDialog() {
      this.userList = [];
    },
    getVisibleStaffList(userIds) {
      getVisibleStaffList({ userIds }).then(res => {
        if (res.code === 200) {
          this.userList = res.data;
        }
      }).catch(err => {
        console.error(err.message);
      });
    },
    showUserInfoDialog(type, list) {
      this.userDialogTitle = type ? '可见人员' : '管理员';
      const userIds = list.join(',');
      this.getVisibleStaffList(userIds);
      this.$refs['userInfoDialogRef'].dialogVisible = true;
    },
    toEdit(item) {
      const routeParams = {
        name: 'ContractProcessEditCustom',
        params: { id: item.id }
      };
      !item.isCustom && (routeParams.query = { isFixed: 1 });
      this.$router.push(routeParams);
    },
    createProcess() {
      this.$router.push({
        name: 'ContractProcessCreateCustom'
      });
    },
    // 创建人 || 表单内权限设置设计表单权限 || 设计表单权限，均可编辑删除
    canDesignForm(rowData) {
      if (!rowData.isCustom) {
        return hasRouteAuth(['crm:legal:formDesign', 'crm:legal:fixedFormDesign']);
      } else {
        return rowData['hasFormDesign'] || hasRouteAuth('crm:legal:formDesign');
      }
    },
    isShow(id) {
      return this.firstLevelIds.includes(id);
    },
    getOpenDetail(row) {
      this.$refs['legalTableRef'].toggleRowExpansion(row);
    },
    batchAdd() {
      this.$refs.batchAdd.openDialog(this.tableSetting);
    },
    groupOperateShow() {
      this.$refs['groupListRef'].dialogVisible = true;
    },
    handleProcessDel(data) {
      showModal('确认删除吗？').then(_ => {
        this.listLoading = true;
        deleteProcess(data.id).then(_ => {
          this.$message.success('删除成功');
          this.getData();
        }).catch(_ => {
          this.listLoading = false;
        });
      });
    },
    handleGroupAdd(data) {
      const { name } = data;
      this.listLoading = true;
      addProcessManagement({ name }).then(_ => {
        this.$message.success('添加成功');
        this.$refs['groupEditRef'].handleDialogClose();
        this.getData();
      }).catch(_ => {
        this.listLoading = false;
      });
    },
    handleGroupEdit(data) {
      const params = {};
      params.id = data.id;
      params.name = data.name;
      params.list = data.children;
      this.listLoading = true;
      editProcessManagement(params).then(_ => {
        this.$message.success('编辑成功');
        this.$refs['groupEditRef'].handleDialogClose();
        this.getData();
      }).catch(_ => {
        this.listLoading = false;
      });
    },
    handleGroupDel(id) {
      this.listLoading = true;
      deleteProcessGroup(id).then(_ => {
        this.$message.success('删除成功');
        this.getData();
      }).catch(_ => {
        this.listLoading = false;
      });
    },
    editDialogShow(data) {
      this.$refs['groupEditRef'].init(data);
    },
    transferAdministrator(row) {
      const { id, type } = row;
      this.transferParam = { id, type };
      this.$refs.auditorDialog.dialogVisible = true;
      this.$refs.auditorDialog.initDeliverTo(1, '管理员转交');
    },
    async sumbmitDeliverTo(val) {
      this.transferParam.administratorId = val.selectUser[0].id;
      try {
        const res = await transferAdministrator(this.transferParam);
        if (res.code === 200) {
          ElMessage.success('转交成功');
          this.getData();
        }
      } catch (err) {
        console.log(err);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.legal-process-container {
  margin: 16px;
  // box-shadow:2px 4px 13px 0px rgba(221,225,234,1);
  // border-radius:12px;
  background-color: #fff;
  padding: 20px;
  height: calc(100vh - 80px);
  .legal-top{
    display: flex;
    justify-content: flex-end;
    margin-bottom: 16px;
    position: relative;
  }
  .flex {
    display: flex;
    align-items: center;
    .module-icon {
      width: 24px;
      height: 24px;
      margin-right: 4px;
      background-color: transparent;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-shrink: 0;
      border-radius: 6px;
      > img {
        width: 14px;
        height: 14px;
      }
    }
  }
  .pointer-class {
    color: #406EFF;
    cursor: pointer;
  }
}
.legal-table {
  min-height: 300px;
  .border-left {
    position: relative;
    padding-left:6px;
    margin-left: 6px;
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 50%;
      margin-top: -7px;
      width: 1px;
      background: #ddd;
      height: 14px;
    }
  }
  &::v-deep {
    .el-table__row:not(.expanded) {
      td {
        border-bottom-color: transparent !important;
        .cell {
          color: #666;
          .el-table__indent, .el-table__placeholder {
            display: none;
          }
        }
      }
    }
    .el-table__row {
      &.expanded {
        .cell {
          font-weight: bold;
          display: flex;
          .el-icon-arrow-right {
            margin-left: 3px;
          }
        }
      }
    }
    .el-table__row--level-1 {
      border-bottom: 1px solid #000;
      td {
        padding: 2px 0;
      }
    }
  }
}
.img-icon {
  width: 14px;
  cursor: pointer;
}
.mobile-table {
  &::v-deep {
    .el-dropdown {
      width: 100%;
      height: 36px;
      button {
        width: calc(100% - 10px);
        height: 100%;
      }
    }
    .pagination-flex {
      border-top: none;
    }
  }
}
</style>
